/*
 *
 *  *  Copyright (c), utrix (idea110@163.com).
 *  *  <p>
 *  *  Licensed under the GNU Lesser General Public License 3.0 (the "License");
 *  *  you may not use this file except in compliance with the License.
 *  *  You may obtain a copy of the License at
 *  *  <p>
 *  * https://www.gnu.org/licenses/lgpl.html
 *  *  <p>
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an "AS IS" BASIS,
 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  * See the License for the specific language governing permissions and
 *  * limitations under the License.
 *
 */

package priv.utrix.micro.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 前端路由权限配置类
 *
 * @author utrix
 * @since 2020/9/28 22:03
 */
@Configuration
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    final WhiteListConfig whiteListConfig;

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 注意: user表中的password加密方式必须与表oauth_client_details中的client_secret加密方式保持一致
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // 重写后在获取token的时候会报异常信息：
    //  provider.endpoint.TokenEndpoint  : Handling error: IllegalStateException, This object has not been built
    // ExceptionHandlerExceptionResolver : Resolved [java.lang.IllegalStateException: This object has not been built]
    // @Override
    // public void init(WebSecurity web) throws Exception {
    //     web.ignoring().antMatchers("/css/**", "/js/**", "/img/**", "/fonts/**");
    // }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .formLogin().loginPage("/login.html").successForwardUrl("/oauth/token").and()
                .authorizeRequests().antMatchers(whiteListConfig.getUrls()).permitAll().anyRequest().authenticated().and()
                .logout().invalidateHttpSession(true).deleteCookies("JSESSIONID");
    }
}
